import router from '@/router'
import setting from './setting'
import nprogress from 'nprogress'
//引入进度条样式
import 'nprogress/nprogress.css'
//进度条的加载圆圈不要
nprogress.configure({ showSpinner: false })

//获取用户相关的小仓库内部token数据，去判断用户是否登陆成功
import useUserStore from './store/modules/user'
//为什么要引pinia
import pinia from './store'
const userStore = useUserStore(pinia)

router.beforeEach(async (to, from, next) => {
    //网页的名字
    console.log(to, from, '111');
    document.title = `${setting.title}-${to.meta.title}`
    nprogress.start()

    if (userStore.token) {
        if (to.path == '/login') {
            next('/')
        } else {
            if (userStore.userInfoMes) {
                next()
            } else {
                try {
                    await userStore.getUserInfo()
                    //万一刷新的时候是异步路由，有可能获取到用户信息但是异步路由没有加载完毕，出现空白效果
                    next({ ...to })
                } catch (error) {
                    await userStore.userLogout()
                    next({ path: '/login', query: { redirect: to.path } })
                }
            }
        }
    } else {
        //用户未登录
        if (to.path == '/login') {
            next()
        } else {
            next({ path: '/login', query: { redirect: to.path } })
        }
    }
})

router.afterEach((to, from) => {
    console.log(to, from, '222');
    nprogress.done()
})